package com.example.usharingtest.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.usharingtest.R;
import com.example.usharingtest.activities.HomepageActivity;
import com.example.usharingtest.service.ServiceUrl;
import com.example.usharingtest.util.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;


import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.exception.BmobException;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;


/**
 * Created by X on 2017/9/11.
 */
public class LoginFragment extends Fragment {
    private static String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    private static String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    SharedPreferences sharedPreferences;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.login,container,false);

        Button getcodebutton = (Button)view.findViewById(R.id.get_code_btn);
        Button loginbutton = (Button)view.findViewById(R.id.login_btn);
        final EditText phonenum = (EditText)view.findViewById(R.id.email);
        final EditText checkcode = (EditText)view.findViewById(R.id.password);

        BmobSMS.initialize(getContext(),"f1ed34525fa1057a8bb091a6e8daf17c");



        getcodebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobSMS.requestSMSCode(getContext(), phonenum.getText().toString(), "usharing", new RequestSMSCodeListener() {
                    @Override
                    public void done(Integer smsid, BmobException e) {
                        if(e == null){
                            //短信发送成功
                            Toast.makeText(getContext(),"验证码发送成功",Toast.LENGTH_SHORT).show();
                            Log.i("bmob","短信id:"+smsid);
                        }
                    }
                });
            }
        });

        loginbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              /* BmobSMS.verifySmsCode(getContext(),phonenum.getText().toString(),checkcode.getText().toString() , new VerifySMSCodeListener() {

                    @Override
                    public void done(BmobException ex) {
                        // TODO Auto-generated method stub
                        if(ex==null){//短信验证码已验证成功
                            Toast.makeText(getContext(),"验证成功，正在登录",Toast.LENGTH_SHORT).show();
                            Log.i("bmob", "验证通过");
                            MyInfoFragment myInfoFragment = new MyInfoFragment();

                            userLogin(phonenum.getText().toString());;
                            FragmentManager fm = getFragmentManager();
                            FragmentTransaction ft = fm.beginTransaction();

                            ft.replace(R.id.study_fragment,myInfoFragment);
                            ft.commit();

                        }else{
                            Toast.makeText(getContext(),"验证失败，请重新验证",Toast.LENGTH_SHORT).show();
                            Log.i("bmob", "验证失败：code ="+ex.getErrorCode()+",msg = "+ex.getLocalizedMessage());
                        }
                    }
                });
*/              sharedPreferences = getActivity().getSharedPreferences("userdata",Context.MODE_PRIVATE);
                Toast.makeText(getContext(),"验证成功，正在登录",Toast.LENGTH_SHORT).show();
                Log.i("bmob", "验证通过");
                MyInfoFragment myInfoFragment = new MyInfoFragment();
                userLogin(phonenum.getText().toString());

                HomepageActivity activity = (HomepageActivity)getActivity();
                activity.onCheckedChanged(R.id.myinfo);
            }
        });

        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    public void userLogin(String phone){
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        String url = ServiceUrl.getUrl(getActivity(), R.string.URL_USER_Login);

        RequestParams parameters = new RequestParams();
        parameters.put("uphone",phone);
        System.out.println("URL="+url);
        asyncHttpClient.setTimeout(11000);   //设置链接超时，如果不设置，默认为10s

        asyncHttpClient.get(url,parameters, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                int userid = -1;
                Log.d("内容", content);
                JSONObject jsonObject = JSONObject.parseObject(content);
                boolean success = jsonObject.getBoolean("success");
                if (success) {
                    userid  = jsonObject.getInteger("data");
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("userid",userid);
                    editor.apply();
                    Log.d("userid :",String.valueOf(userid));
                }
            }
            @Override
            public void onFailure(Throwable error, String content) {
                System.out.println("连接失败");
                Toast.makeText(getActivity(), "服务器连接错误" , Toast.LENGTH_SHORT).show();
            }
        });
    }
}


